package io.github.codelifeleno.jdbrelease.spring.boot;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import io.github.codelifeleno.jdbrelease.config.JDBReleaseConfig;
import io.github.codelifeleno.jdbrelease.execute.JDBReleaseInit;
import io.github.codelifeleno.jdbrelease.execute.JDBReleaseService;
import io.github.codelifeleno.jdbrelease.model.JDBReleaseRunModel;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;

@Service
public class AutoService {

    private AutoProperties properties;

    public AutoService(AutoProperties properties) {
        this.properties = properties;
    }

    public AutoProperties getProperties() {
        return properties;
    }

    public void execute(DataSource dataSource) throws IOException, URISyntaxException {
        String jdbReleaseConfigFilePath = properties.getFilePath();
        String runId = DateUtil.format(new Date(), "yyyyMMdd_HHmm");
        JDBReleaseRunModel runModel = new JDBReleaseRunModel(runId, ResourceUtil.getResourceObj(jdbReleaseConfigFilePath));
        JDBReleaseInit init = new JDBReleaseInit();
        JDBReleaseConfig jdbReleaseConfig = init.initConfig(ResourceUtil.getResourceObj(jdbReleaseConfigFilePath));
        JDBReleaseService jdbReleaseService = new JDBReleaseService(jdbReleaseConfig);
        jdbReleaseService.executeAllByDatasource(runModel, dataSource);
    }
}
